
import { TraShenQingApi, TraShenQingHuanZheInput, TraShenQingInput, TraShenQingYongXueInput, TraShuXueQianJianYanInfo } from '/@/api/tra/TraShenQing';
import { TraKuaiSuFaXueMingXiInput, TraKuaiSuFaXueApi } from '/@/api/tra/TraKuaiSuFaXue';
import { BasShuXueJianYanApi, BasShuXueJianYanOutput } from '/@/api/bas/BasShuXueJianYan';
import { InvKuCunOutput } from '/@/api/inv/InvKuCun';
import { TraFuHeApi, TraFuHeInput } from '/@/api/tra/TraFuHe';
import { TraFaXueApi, TraFaXueInput } from '/@/api/tra/TraFaXue';
import { enumCode } from '/@/const';
import { showError, showSuccess } from '/@/utils';
import { useConfirmDialog } from '/@/hooks/useConfirmDialog'
import { TraShenQingJianYanInput } from '/@/api/tra/TraShenQing/dto/TraShenQingJianYanInput';
import { ElMessageBox } from 'element-plus';
import { getXueYePinZhongInfo, loginInfo } from '/@/stores/baseInfo';



// 定义各个组件的引用
export const billPanelRef = ref();
// 患者表单组件的引用
export const huanZheFormRef = ref();
// 申请用血表单组件的引用
export const shenQingYongXueFormRef = ref();
// 复核表单组件的引用
export const fuHeFormRef = ref();
// 快速发血表单组件的引用
export const kuaiSuFaXueFromRef = ref();
export const listRef = ref();
export const scanRef = ref();

/**
 * 初始化状态的函数
 * @returns 返回一个包含初始状态的对象
 */
const initialState = () => {
  return {
    // 是否处于编辑状态
    isEdit: true,
    // 控制每个模块是否可修改
    editControl: {
      huanZheIsEdit: true,
      shenQingIsEdit: true,
      shenQingYongXueIsEdit: true,
      fuHeIsEdit: true,
      faXueIsEdit: true,
      faXueMingXiIsEdit: true
    },
    // 是否显示更多患者信息
    isMorePatientInfo: false,
    // 是否正在加载数据
    loading: false,
    // 输血申请输入数据、主表
    traShenQingInput: {
      createUserName: loginInfo.value.realName
    } as TraShenQingInput,
    // 输血申请患者输入数据，默认输血史、反应史、移植配型史、孕产史均为 '无'
    traShenQingHuanZheInput: {
      shuXueShi: '无',
      shuXueFanYingShi: '无',
      yunChanShi: '无',
      yiZhiShi: '无',
    } as TraShenQingHuanZheInput,
    faXue: { danJuLeiXing: '快速发血' } as TraFaXueInput,
    // 输血申请用血输入数据
    traShenQingYongXueInput: {
      yongXueLeiXing: ''
    } as TraShenQingYongXueInput,
    shenQingPinZhongDanWei: '',
    // 输血申请复核输入数据
    traFuHeInput: {} as TraFuHeInput,
    // 快速发血明细列表，类型为 TraKuaiSuFaXueMingXiInput 数组
    traKuaiSuFaXueMingXiList: [] as TraKuaiSuFaXueMingXiInput[],
    // 申请检验列表
    traShuXueQianJianYanInfo: [] as TraShuXueQianJianYanInfo[],
    // 基础输血检验信息列表
    basShuXueJianYanList: [] as BasShuXueJianYanOutput[]

  };
};

// 创建一个响应式的上下文对象，初始值为 initialState 函数的返回值
export const ctx = reactive(initialState());
//#region 单据的处理
/**
 * 创建一个新的实体，将上下文对象重置为初始状态并设置为编辑状态
 */
export const newEntity = () => {
  // 将上下文对象重置为初始状态
  Object.assign(ctx, initialState());
  // 设置为编辑状态
  ctx.isEdit = true;
  // 不显示更多患者信息
  ctx.isMorePatientInfo = false;
}
export const checkIsInThreeDay = () => {
  if (!ctx.faXue.createTime) return false
  // 检查 ctx.faXue.createTime 是否在72小时内
  // 获取当前时间
  const now = new Date();
  const createTime = new Date(ctx.faXue.createTime);
  const timeDiff = now.getTime() - createTime.getTime();
  const hoursDiff = timeDiff / (1000 * 60 * 60);
  // 判断是否在 72 小时内
  return hoursDiff <= 72;
}
/**
 * 加载实体数据
 * @param row 包含实体 ID 的对象
 */
export const loadEntity = (row) => {
  if (!row || !row.id) return;
  // 设置加载状态为 true
  ctx.loading = true;
  // 调用快速发血信息 API 获取数据
  TraKuaiSuFaXueApi.kuaiSuFaXueMessage(row.id).then(res => {
    // 打印获取到的数据
    console.log(res);
    ctx.isEdit = false;
    Object.keys(ctx.editControl).forEach(key => {
      ctx.editControl[key] = false;
    })
    ctx.faXue = res.faXue;
    ctx.traShenQingInput = res.shenQing;
    ctx.traShenQingHuanZheInput = res.huanZhe;
    ctx.traShenQingYongXueInput = res.yongXue;
    ctx.traFuHeInput = res.shenQingFuHe;
    ctx.traKuaiSuFaXueMingXiList = res.traKuaiSuFaXueMingXiList;
  }).finally(() => {
    // 无论请求成功或失败，都将加载状态设置为 false
    ctx.loading = false;
  })
}
/** 修改患者信息 */
export const updateHuanZhe = async () => {
  if (ctx.loading) return;
  if (!checkIsInThreeDay()) {
    showError('单据已创建超过72小时，无法修改')
  }
  // 验证患者表单是否有效
  const isHuanZheVaild = await huanZheFormRef.value?.validate();
  if (!isHuanZheVaild) return;
  ctx.loading = true;
  TraShenQingApi.updateHuanZhe(ctx.traShenQingHuanZheInput).then(res => {
    showSuccess('保存成功');
    ctx.editControl.huanZheIsEdit = false;
  }).finally(() => {
    ctx.loading = false;
  })
}
/** 修改申请用血信息 */
export const updateYongXue = async () => {
  if (ctx.loading) return;
  if (!checkIsInThreeDay()) {
    showError('单据已创建超过72小时，无法修改')
  }
  const isShenQingYongXueVaild = await shenQingYongXueFormRef.value?.validate();
  if (!isShenQingYongXueVaild) return;
  ctx.loading = true;
  TraShenQingApi.updateYongXueShenQingXinXi({
    traShenQingInput: ctx.traShenQingInput,
    traShenQingYongXueInput: ctx.traShenQingYongXueInput,
  }).then(res => {
    showSuccess('保存成功');
    ctx.editControl.shenQingYongXueIsEdit = false;
  }).finally(() => {
    ctx.loading = false;
  })
}
/** 修改复核信息 */
export const updateFuHe = async () => {
  if (ctx.loading) return;
  if (!checkIsInThreeDay()) {
    showError('单据已创建超过72小时，无法修改')
  }
  const isFuHeVaild = await fuHeFormRef.value?.validate();
  if (!isFuHeVaild) return;
  TraFuHeApi.update(ctx.traFuHeInput).then(res => {
    showSuccess('保存成功');
    ctx.editControl.fuHeIsEdit = false;
  }).finally(() => {
    ctx.loading = false;
  })
}
/** 修改发血信息 */
export const updateFaXue = async () => {
  if (ctx.loading) return;
  if (!checkIsInThreeDay()) {
    showError('单据已创建超过72小时，无法修改')
  }
  const isKuaiSuFaXueVaild = await kuaiSuFaXueFromRef.value?.validate();
  if (!isKuaiSuFaXueVaild) return;
  ctx.loading = true;
  TraFaXueApi.updateZhuBiao(ctx.faXue).then(res => {
    showSuccess('保存成功');
    ctx.editControl.faXueIsEdit = false;
  }).finally(() => {
    ctx.loading = false;
  })
}
export const updateFaXueMingXi = async () => {
  if (ctx.loading) return;
  if (!checkIsInThreeDay()) {
    showError('单据已创建超过72小时，无法修改')
  }
  if (ctx.traKuaiSuFaXueMingXiList.length == 0) {
    let isContinue = false
    await ElMessageBox.confirm('当前发血明细未录入血液，是否确定保存？', '提示', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      isContinue = true;
    })
    if (!isContinue) return;
  }
  ctx.loading = true;
  const params = {
    id: ctx.faXue.id,
    traKuaiSuFaXueMingXiList: ctx.traKuaiSuFaXueMingXiList,
  }
  TraKuaiSuFaXueApi.updateFaXueMingXi(params).then(res => {
    showSuccess('保存成功');
    ctx.editControl.faXueMingXiIsEdit = false;
  }).finally(() => {
    ctx.loading = false;
  })
}
/**
 * 提交表单数据
 */
export const submit = async () => {
  if (ctx.loading) return;

  // 验证患者表单是否有效
  const isHuanZheVaild = await huanZheFormRef.value?.validate();
  if (!isHuanZheVaild) return;
  // 验证申请用血表单是否有效
  const isShenQingYongXueVaild = await shenQingYongXueFormRef.value?.validate();
  if (!isShenQingYongXueVaild) return;
  // 验证复核表单是否有效
  const isFuHeVaild = await fuHeFormRef.value?.validate();
  if (!isFuHeVaild) return;
  // 验证快速发血表单是否有效
  const isKuaiSuFaXueVaild = await kuaiSuFaXueFromRef.value?.validate();
  if (!isKuaiSuFaXueVaild) return;

  // 如果快速发血明细列表为空，则显示错误信息并返回
  if (ctx.traKuaiSuFaXueMingXiList.length == 0) return showError('请录入血液信息');
  // 组装提交的参数
  const param = {
    traShenQingInput: ctx.traShenQingInput,
    traShenQingHuanZheInput: ctx.traShenQingHuanZheInput,
    traShenQingYongXueInput: ctx.traShenQingYongXueInput,
    traFuHeInput: ctx.traFuHeInput,
    traKuaiSuFaXueMingXiList: ctx.traKuaiSuFaXueMingXiList,
    // 拼接检验信息
    traShenQingJianYanList: ctx.traShuXueQianJianYanInfo.map((item) => {
      return {
        traShenQingId: ctx.traShenQingInput.id,
        basJianYanId: item.basJianYanId,
        basJianYanMingCheng: item.basJianYanMingCheng,
        jieGuo: item.jieGuo,
        jianYanShiJian: item.jianYanShiJian,
      } as TraShenQingJianYanInput;
    }),
    shuXueQianTiWen: ctx.faXue.shuXueQianTiWen,
    quXueRenId: ctx.faXue.quXueRenId,
    quXueRen: ctx.faXue.quXueRen,
    remark: ctx.faXue.remark,
  }
  ctx.loading = true;
  TraKuaiSuFaXueApi.kuaiSuFaXue(param).then(res => {
    showSuccess('保存成功');
    loadEntity({ id: res })
  }).finally(() => {
    ctx.loading = false;
  })
}

/**  审核 */
export const audit = async () => {
  if (ctx.loading) return;
  if (!ctx.faXue.id) return showError('请先保存数据');
  if (Object.keys(ctx.editControl).some(key => ctx.editControl[key])) {
    let isContinue = false
    await ElMessageBox.confirm('存在编辑中的模块未保存，是否继续审核', '提示', {
      confirmButtonText: '继续审核',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      isContinue = true;
    })
    if (!isContinue) return;
  }
  if (ctx.traKuaiSuFaXueMingXiList.length == 0) return showError('未录入血液信息，无法审核！');
  const auditParam = {
    id: ctx.faXue.id,
    quXueRenId: ctx.faXue.quXueRenId,
  }
  ctx.loading = true;
  TraKuaiSuFaXueApi.audit(auditParam).then(res => {
    showSuccess('审核成功');
    loadEntity({ id: ctx.traShenQingInput.id })
  }).finally(() => {
    ctx.loading = false;
  })
}
/** 获取检验信息 */
export const getJianYanList = () => {
  BasShuXueJianYanApi.checkShuXueJianYanList().then(res => {
    ctx.basShuXueJianYanList = res;
    setTraShenQingJianYan();
  })
}
/** 设置输血前输血检验项目 */
const setTraShenQingJianYan = () => {
  // 返回输血前检验项目信息
  ctx.traShuXueQianJianYanInfo = ctx.basShuXueJianYanList.map(item => {
    return {
      traShenQingId: '',
      basJianYanId: item.id,
      basJianYanMingCheng: item.mingCheng,
      jieGuo: '',
      danWei: item.danWei,
      basJianYanJianCheng: item.jianCheng,
    } as TraShuXueQianJianYanInfo;
  })
  console.log(ctx.traShuXueQianJianYanInfo);

}
//#endregion
//#region change事件处理
export const handlePinZhongChange = (val) => {
  if (!val) {
    ctx.shenQingPinZhongDanWei = '';
  }
  const pinZhong = getXueYePinZhongInfo(val);
  ctx.shenQingPinZhongDanWei = pinZhong?.danWei ?? '';
}
//#endregion
//#region 打印处理
/**
 * 打印功能，目前为空实现
 */
export const print = () => {
  billPanelRef.value.printWeb(ctx.faXue.id, '', '');
}
//#endregion

//#region 血液处理
/**
 * 扫描血液信息并处理
 * @param blood 库存血液信息
 */
export const scanEnter = (blood: InvKuCunOutput) => {
  console.log(blood);
  // 如果血液不在库中，则显示错误信息并返回
  if (blood.kuCunZhuangTai != enumCode.KuCunZhuangTai.在库) return showError('该血液不在库中');
  // 如果该血液已录入，则显示错误信息并返回
  if (ctx.traKuaiSuFaXueMingXiList.find(item => item.invKuCun?.id == blood.id)) return showError('该血液已录入');

  // 将扫描到的血液信息添加到快速发血明细列表中
  ctx.traKuaiSuFaXueMingXiList.push({
    invKuCun: blood
  })
}
export const delBlood = (row: TraKuaiSuFaXueMingXiInput) => {
  useConfirmDialog(`是否确认删除此数据`).then(() => {
    ctx.traKuaiSuFaXueMingXiList = ctx.traKuaiSuFaXueMingXiList.filter(item => item.invKuCun?.id != row.invKuCun?.id);
  })

}
//#endregion